package com.creative.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by yinjialiang on 15-4-30.
 */
public class XTextWatcher implements TextWatcher {
    private EditText editText;
    private int maxLength;
    private int currentEnd;

    /**
     *
     * @param editText
     * @param maxLength 0表示不限制
     */
    public XTextWatcher(EditText editText, int maxLength)
    {
        this.editText = editText;
        this.maxLength = maxLength;
    }
    public XTextWatcher(EditText editText)
    {
        this(editText, 0);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        char [] cc = s.toString().toCharArray();
        for (int i = 0; i < cc.length; i++) {
            if(String.valueOf(cc[i]).equals("\n")){
                String string = "";
                for (int j = 0; j < cc.length; j++) {
                    if(!String.valueOf(cc[j]).equals("\n")){
                        string += String.valueOf(cc[j]);
                    }
                }
                editText.setText(string);
                if(start <= string.length()) {
                    editText.setSelection(start);
                }
                return;
            }
        }
        currentEnd = start+count;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        while (calculateLength(s) > maxLength) { // 若變化後的長度超過最大長度
            // 刪除最後變化的字元
            currentEnd--;
            s.delete(currentEnd, currentEnd + 1);
        }
    }

    protected int calculateLength(final CharSequence c) {
        int len = 0;
        final int l = c.length();
        for (int i = 0; i < l; i++) {
            final char tmp = c.charAt(i);
            if (tmp >= 0x20 && tmp <= 0x7E) {
                // 字元值 32~126 是 ASCII 半形字元的範圍
                len++;
            } else {
                // 非半形字元
                len += 2;
            }
        }
        return len;
    }
}
